package cn.com.reflect;

import cn.com.domain.Person;

import java.lang.reflect.Field;

public class ReflectDemo1 {
    public static void main(String[] args)  throws Exception{
        Class personClass = Person.class;

        System.out.println("获取public的成员变量：");
        System.out.println("---------------------------------");
        Field[] fields = personClass.getFields();
        for (Field field1:fields
             ) {
            System.out.println(field1);
        }

        System.out.println("---------------------------------");

        System.out.println("定义一个person对象，给person对象的属性a赋值");
        Field field = personClass.getField("a");
        Person person=new Person();
        Object values = field.get(person);
        System.out.println(values);
        System.out.println(person.getA());
        System.out.println(field.get(person));

        field.set(person,"狗逼");
        values=field.get(person);
        System.out.println(values);
        System.out.println(person.getA());
        System.out.println(field.get(person));


        System.out.println("----------------------------");
        System.out.println("获取所有的的属性");
        System.out.println("--------------------------------");
        Field[] declaredFields = personClass.getDeclaredFields();
        for (Field field2:declaredFields
             ) {
            System.out.println(field2);
        }

        System.out.println("--------------------------------");
        System.out.println("给任意属性赋值");
        Field d = personClass.getDeclaredField("d");
        d.setAccessible(true);
        d.set(person,"颜儿沟");
        System.out.println(person.toString());
        System.out.println(person.getD());
        System.out.println(d.get(person));
    }


}
